<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="维修任务ID" prop="repairTaskId">
        <el-input
          v-model="queryParams.repairTaskId"
          placeholder="请输入维修任务ID"
          clearable
          :size="'small'"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评价人" prop="evaluator">
        <el-input
          v-model="queryParams.evaluator"
          placeholder="请输入评价人"
          clearable
          :size="'small'"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="满意度" prop="evaluationResult">
        <el-select v-model="queryParams.evaluationResult" placeholder="请选择满意度" clearable :size="'small'">
          <el-option label="非常满意" value="非常满意" />
          <el-option label="满意" value="满意" />
          <el-option label="一般" value="一般" />
          <el-option label="不满意" value="不满意" />
          <el-option label="非常不满意" value="非常不满意" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="Plus"
          :size="'mini'"
          @click="handleAdd"
          v-hasPermi="['qep:repair-evaluation:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :icon="Edit"
          :size="'mini'"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['qep:repair-evaluation:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :icon="Delete"
          :size="'mini'"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['qep:repair-evaluation:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="repairEvaluationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="50"/>
      <el-table-column label="维修任务ID" align="center" prop="repairTaskId" />
      <el-table-column label="评价人" align="center" prop="evaluator" />
      <el-table-column label="满意度" align="center" prop="evaluationResult">
        <template #default="scope">
          <el-tag :type="scope.row.evaluationResult === '非常满意' ? 'success' : 
                         scope.row.evaluationResult === '满意' ? 'success' :
                         scope.row.evaluationResult === '一般' ? 'warning' :
                         scope.row.evaluationResult === '不满意' ? 'danger' : 'danger'">
            {{ scope.row.evaluationResult }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="评价时间" align="center" prop="evaluationDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.evaluationDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="评价内容" align="center" prop="evaluationComment" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            :size="'mini'"
            link
            :icon="View"
            @click="handleView(scope.row)"
            v-hasPermi="['qep:repair-evaluation:query']"
          >查看</el-button>
          <el-button
            :size="'mini'"
            link
            :icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['qep:repair-evaluation:edit']"
          >修改</el-button>
          <el-button
            :size="'mini'"
            link
            :icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qep:repair-evaluation:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改维修评价对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="维修任务ID" prop="repairTaskId">
          <el-input v-model="form.repairTaskId" placeholder="请输入维修任务ID" />
        </el-form-item>
        <el-form-item label="评价人" prop="evaluator">
          <el-input v-model="form.evaluator" placeholder="请输入评价人" />
        </el-form-item>
        <el-form-item label="满意度" prop="evaluationResult">
          <el-select v-model="form.evaluationResult" placeholder="请选择满意度">
            <el-option label="非常满意" value="非常满意" />
            <el-option label="满意" value="满意" />
            <el-option label="一般" value="一般" />
            <el-option label="不满意" value="不满意" />
            <el-option label="非常不满意" value="非常不满意" />
          </el-select>
        </el-form-item>
        <el-form-item label="评价内容" prop="evaluationComment">
          <el-input v-model="form.evaluationComment" type="textarea" placeholder="请输入评价内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 维修评价详情对话框 -->
    <el-dialog title="维修评价详情" v-model="viewOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="维修任务ID">{{ form.repairTaskId }}</el-descriptions-item>
        <el-descriptions-item label="评价人">{{ form.evaluator }}</el-descriptions-item>
        <el-descriptions-item label="满意度">
          <el-tag :type="form.evaluationResult === '非常满意' ? 'success' :
                         form.evaluationResult === '满意' ? 'success' :
                         form.evaluationResult === '一般' ? 'warning' :
                         form.evaluationResult === '不满意' ? 'danger' : 'danger'">
            {{ form.evaluationResult }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="评价时间">
          {{ parseTime(form.evaluationDate, '{y}-{m}-{d} {h}:{i}:{s}') }}
        </el-descriptions-item>
        <el-descriptions-item label="评价内容" :span="2">{{ form.evaluationComment }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ parseTime(form.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ form.remark }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listRepairEvaluation, getRepairEvaluation, addRepairEvaluation, updateRepairEvaluation, delRepairEvaluation, getRepairEvaluationByTaskId } from "@/api/qep/repairEvaluation";
import { Search, Refresh, Plus, Edit, Delete, View } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: "RepairEvaluation",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 维修评价表格数据
      repairEvaluationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      viewOpen: false,
      // 维修任务选项
      repairTaskOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        repairTaskId: null,
        evaluator: null,
        evaluationResult: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        repairTaskId: [
          { required: true, message: "维修任务ID不能为空", trigger: "blur" }
        ],
        evaluator: [
          { required: true, message: "评价人不能为空", trigger: "blur" }
        ],
        evaluationResult: [
          { required: true, message: "满意度不能为空", trigger: "change" }
        ],
        evaluationComment: [
          { required: true, message: "评价内容不能为空", trigger: "blur" }
        ]
      },
      // 图标
      Search, Refresh, Plus, Edit, Delete, View
    };
  },
  created() {
    // 从路由参数中获取维修任务ID（如果有）
    if (this.$route.query.taskId) {
      this.queryParams.repairTaskId = this.$route.query.taskId;
      
      // 检查是否已经存在此维修任务的评价
      getRepairEvaluationByTaskId(this.$route.query.taskId).then(response => {
        if (response.data) {
          // 如果已存在评价，显示该评价
          ElMessage.info("该维修任务已有评价记录");
          this.getList();
        } else {
          // 如果不存在评价，自动弹出创建评价的窗口
          this.handleAddFromTask(this.$route.query.taskId);
        }
      }).catch(() => {
        // API调用失败，尝试直接创建新评价
        this.handleAddFromTask(this.$route.query.taskId);
      });
    }
    this.getList();
  },
  methods: {
    /** 查询维修评价列表 */
    getList() {
      this.loading = true;
      listRepairEvaluation(this.queryParams).then(response => {
        this.repairEvaluationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        repairTaskId: this.queryParams.repairTaskId || null,
        evaluator: null,
        evaluationResult: null,
        evaluationComment: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加维修评价";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getRepairEvaluation(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改维修评价";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 在提交前自动设置评价时间为当前日期
          const formData = {
            ...this.form,
            evaluationDate: this.formatCurrentTime()
          };
          
          if (this.form.id != null) {
            updateRepairEvaluation(formData).then(response => {
              ElMessage.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRepairEvaluation(formData).then(response => {
              ElMessage.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      ElMessageBox.confirm('是否确认删除维修评价编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delRepairEvaluation(ids);
      }).then(() => {
        this.getList();
        ElMessage.success("删除成功");
      }).catch(() => {
        // 用户取消操作时不处理
      });
    },
    /** 查看详情按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id;
      getRepairEvaluation(id).then(response => {
        this.form = response.data;
        this.viewOpen = true;
      });
    },
    
    /** 从维修任务创建评价 */
    handleAddFromTask(taskId) {
      this.reset();
      this.form.repairTaskId = taskId;
      // 设置默认值
      this.form.evaluator = localStorage.getItem('userName') || '';
      
      this.open = true;
      this.title = "添加维修评价";
    },
    /** 格式化当前时间为 yyyy-MM-dd HH:mm:ss 格式 
     * 我们已经修改了后端Java实体类的@JsonFormat注解为pattern="yyyy-MM-dd HH:mm:ss"
     * 现在可以保存和显示完整的时间信息
     */
    formatCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      
      // 返回格式化的日期时间字符串 (yyyy-MM-dd HH:mm:ss)
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
  }
};
</script> 